package com.qidian.buy.cart.interceptors;

import com.qidian.buy.entity.User;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @date 2023/5/26 15:07
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RestTemplate restTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置允许跨域请求数据
        //允许所有的域  所有的源请求数据
        response.setHeader("Access-Control-Allow-Origin","*");
        // 设置允许跨域请求数据  允许携带任何请求头跨域
        response.setHeader("Access-Control-Allow-Headers", "*");
        //允许所有的请求方法访问  如post , get方法
        response.setHeader("Access-Control-Allow-Method", "*");

        // 从请求头中取出token
        String token = request.getHeader("token");
        if(token != null && !"".equals(token)){
            // 远程调用，查询用户信息
            BuyResult buyResult = restTemplate.getForObject("http://buy-sso/buy/user/checkLogin?token=" + token, BuyResult.class);
            if(buyResult.getCode() == 200 || buyResult.getObj()!=null){
                Map map = (Map) buyResult.getObj();
                // 由与obj是hashMap，所以我们将hashMap转换为user
                User user = new User();
                user.setId(new Long(map.get("id").toString()));
                // 将用户信息放入request的作用域
                request.setAttribute("user",user);
                // 放行
                return true;
            }
        }
        // 响应客户端
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONTools.object2json(BuyResult.fal("未登录")));
        return false;
    }
}
